package cn.whx.hrm.service.impl;

import cn.whx.hrm.LoginUserConstant;
import cn.whx.hrm.constatan.RegistConstant;
import cn.whx.hrm.domain.LoginUser;
import cn.whx.hrm.domain.VipUser;
import cn.whx.hrm.dto.RegistDto;
import cn.whx.hrm.feign.LoginUserFeignClient;
import cn.whx.hrm.mapper.VipUserMapper;
import cn.whx.hrm.service.IVipUserService;
import cn.whx.hrm.util.AjaxResult;
import cn.whx.hrm.util.BitStatesUtils;
import cn.whx.hrm.util.ValidUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.Valid;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author whx
 * @since 2021-06-25
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginUserFeignClient loginUserFeignClient;
    @Autowired
    private VipUserMapper vipUserMapper;

    @Override
    public AjaxResult register(@Valid RegistDto registDto) {
        //判断手机验证码
        String key = RegistConstant.REGIST_KEY+"::"+registDto.getMobile();
        Object obj = redisTemplate.opsForValue().get(key);
        ValidUtils.assertNotNull(obj,"手机验证码失效");
        String code = obj.toString();//强转
        String smsCode = registDto.getSmsCode().trim();
        if (!code.equals(smsCode)){
            throw new RuntimeException("手机验证码错误");
        }
        //校验通过就保存到用户信息里面去，保存到auth服务的保存到t_vip_user
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(registDto.getMobile());
        loginUser.setPassword(registDto.getPassword());
        loginUser.setType(LoginUserConstant.LOGIN_GENERAL_ADMIN);
        AjaxResult result = loginUserFeignClient.addOrUpdate(loginUser);
        //判断auth保存成功
        if (!result.isSuccess()){
            throw new RuntimeException("保存失败");

        }
        Integer resultObj = (Integer) result.getResultObj();
        //保存到vipuser
        VipUser vipUser = new VipUser();
        vipUser.setPhone(registDto.getMobile());
        vipUser.setPhone(registDto.getMobile());
        vipUser.setPassword(registDto.getPassword());
        long date = System.currentTimeMillis();
        vipUser.setCreateTime(date);
        vipUser.setLoginId(Long.valueOf(resultObj));
        //状态单独处理
        long state = BitStatesUtils.OP_REGISTED;
        long state2 = BitStatesUtils.addState(state, BitStatesUtils.OP_ACTIVED);
        long saste3 = BitStatesUtils.addState(state2, BitStatesUtils.OP_IDENTITY_AUTHED);
        vipUser.setBitState(saste3);
        vipUserMapper.insert(vipUser);
        return result;
    }
}
